# -*- encoding: utf-8 -*-
"""
PyCharm main
2022年01月04日
by littlefean
"""
from win10toast import ToastNotifier

import json
from datetime import datetime
from time import sleep
import threading

# import win32com.client
# from winsound import Beep
from flask import Flask
from flask import request
from flask_cors import *  # 导入模块

# speaker = win32com.client.Dispatch('SAPI.SPVOICE')
notifier = ToastNotifier()
app = Flask(__name__)
CORS(app, supports_credentials=True)


def getArrObjFromFile(filePath: str) -> list:
    """
    解析一个json文件，获取列表对象
    :param filePath: 文件路径
    :return: python的list对象
    """
    try:
        with open(filePath, encoding="utf-8") as f:
            content = f.read()
    except UnicodeError:
        with open(filePath, encoding="ANSI") as f:
            content = f.read()
    except FileNotFoundError:
        with open(filePath, "w", encoding="utf-8") as f:
            f.write("[]")
        content = ""
    if content.strip() == "":
        arr = []
    else:
        arr = json.loads(content)
    return arr


todoList = getArrObjFromFile("todoList.json")
alreadyList = getArrObjFromFile("alreadyList.json")


@app.route('/getInit')
def getInit():
    """
    界面一打开的获取函数
    待办事项 [{name:xxx, date:xxx, time:xxx}, {}, ...]
    已完成事项 [{name:xxx, date:xxx, time:xxx}, {}, ...]
    :return: 返回json字符串 {todoList:[], alreadyList:[]}
    """
    res = {
        # "todoList": getArrObjFromFile("todoList.json"),
        "todoList": todoList,
        "alreadyList": alreadyList,
        # "alreadyList": getArrObjFromFile("alreadyList.json")
    }
    return json.dumps(res, ensure_ascii=False)


@app.route('/delTodoEvent', methods=['POST'])
def delTodoEvent():
    """
    删除一个todoList里的事件
    :return: 删除成功字符串
    """
    data = json.loads(request.get_data(as_text=True))
    print("准备删除的数据：", data, type(data))
    # arr = getArrObjFromFile("todoList.json")
    if data in todoList:
        todoList.remove(data)
        print("删除后的数组", todoList)
        # open("todoList.json", "w").write(json.dumps(todoList, ensure_ascii=False))
        print("删除成功", data)
        return "删除成功"
    else:
        print("原来的数据库中已经没有这个数据了")
        return "原来的数据库中已经没有这个数据了"


@app.route('/delReadyEvent', methods=['POST'])
def delReadyEvent():
    """
    删除一个readList里面的事件
    :return:
    """
    data = json.loads(request.get_data(as_text=True))
    print("准备删除的数据：", data, type(data))
    # arr = getArrObjFromFile("alreadyList.json")
    if data in alreadyList:
        alreadyList.remove(data)
        # open("alreadyList.json", "w").write(json.dumps(alreadyList, ensure_ascii=False))
        print("删除成功")
        return ""
    return ""


@app.route('/addTodoEvent', methods=['POST'])
def addTodoEvent():
    data = json.loads(request.get_data(as_text=True))
    print("准备添加的数据：", data, type(data))
    # arr = getArrObjFromFile("todoList.json")
    todoList.append(data)
    # open("todoList.json", "w").write(json.dumps(todoList, ensure_ascii=False))
    return "添加成功"


@app.route('/addReadyEvent', methods=['POST'])
def addReadyEvent():
    """
    添加一个事件到readyList里面
    :return: 添加成功消息
    """
    data = json.loads(request.get_data(as_text=True))
    print("准备添加的数据：", data, type(data))
    # arr = getArrObjFromFile("alreadyList.json")
    alreadyList.append(data)
    # open("alreadyList.json", "w").write(json.dumps(alreadyList, ensure_ascii=False))
    print("alreadyList添加成功", data)
    return "添加成功"


@app.route('/checkReadyEvent')
def checkReadyEvent():
    """返回给前端已经过期了的事件"""
    res = []
    print("检查列表中有没有到期的事：", todoList)
    now = datetime.now()
    for eve in todoList:
        t = datetime.strptime(eve["date"] + " " + eve["time"], '%Y-%m-%d %H:%M:%S')
        if t < now:
            res.append(eve)
            # 应该自动将这个事情移动到已经完成的事情里面
    return json.dumps(res, ensure_ascii=False)


def interval():
    while True:
        removeArr = []
        now = datetime.now()
        for eve in todoList:
            t = datetime.strptime(eve["date"] + " " + eve["time"], '%Y-%m-%d %H:%M:%S')
            if t < now:
                removeArr.append(eve)
                notifier.show_toast(eve["name"], "事程系统的提醒", icon_path="notice.ico", duration=6, threaded=True)
        for eve in removeArr:
            todoList.remove(eve)
            alreadyList.append(eve)
        sleep(10)


def autoSave():
    print("保存线程开启")
    while True:
        # print("====开始自动保存")
        open("alreadyList.json", "w").write(json.dumps(alreadyList, ensure_ascii=False))
        open("todoList.json", "w").write(json.dumps(todoList, ensure_ascii=False))
        # print("\ttodoList:", todoList)
        # print("\talreadyList:", alreadyList)
        # print("====已经自动保存了一次")
        sleep(60)


def main():
    print("服务器开始运行了")
    print("app run")
    threading.Thread(target=autoSave).start()
    threading.Thread(target=interval).start()
    app.run(port=10086)
    return None


if __name__ == "__main__":
    main()
